package com.eternal.log;

import android.annotation.SuppressLint;

import androidx.lifecycle.Observer;
import androidx.paging.PagedList;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.eternal.base.concat.BluetoothEvent;
import com.eternal.base.concat.LogExtra;
import com.eternal.base.data.RepositoryInjection;
import com.eternal.base.database.entity.Log;
import com.eternal.base.global.ActivityEvent;
import com.eternal.base.router.RouterFragmentPath;
import com.eternal.framework.binding.command.BindingAction;
import com.eternal.framework.bus.Messenger;
import com.eternal.framework.bus.RxBus;
import com.eternal.framework.component.BaseFragment;
import com.eternal.framework.utils.KLog;
import com.eternal.log.adapter.LogAdapter;
import com.eternal.log.databinding.FragmentHistoryBinding;
import com.eternal.log.model.LogModel;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator
 * On 2020/5/12
 * Description:
 *
 * @author Administrator
 */
@Route(path = RouterFragmentPath.Log.PAGE_LOG)
public class LogFragment extends BaseFragment<FragmentHistoryBinding, LogModel> {
    public static final String REFRESH_LOG = "refresh log";

    private LogAdapter adapter;
    private LogObservable observable;
    private int position;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_history;
    }

    @Override
    public int initVariableId() {
        return BR.model;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        bindEvent();
        registerMassage();
    }


    @Override
    public void onDestroyView() {
        unregisterMassage();
        super.onDestroyView();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        final GestureDetector detector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                if (Math.abs(distanceY) > Math.abs(distanceX) && distanceY < 0 && !adapter.isClear()) {
                    viewModel.resetTime();
                    adapter.clear();
                    //发送消息到DetailActivity控制log角标显示
                    RxBus.getDefault().post(new BluetoothEvent(BluetoothEvent.REFRESH_BADGE, viewModel.mac, 0));
                    return true;
                }
                return false;
            }
        });

        binding.rcContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (viewModel.show.getValue() == Boolean.FALSE) {
                        viewModel.show.setValue(true);
                    }
                }
                return detector.onTouchEvent(event);
            }
        });
        binding.rcContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
//                if (Math.abs(recyclerView.getY()) > Math.abs(recyclerView.getX()) && recyclerView.getY() > 0 && !adapter.isClear()) {
//                    viewModel.resetTime();
//                    adapter.clear();
//                    //发送消息到DetailActivity控制log角标显示
//                    RxBus.getDefault().post(new BluetoothEvent(BluetoothEvent.REFRESH_BADGE, viewModel.mac, 0));
//                }
                if (recyclerView.getChildCount() > 0) {
                    try {
                        position = ((RecyclerView.LayoutParams) recyclerView.getChildAt(0).getLayoutParams()).getViewAdapterPosition();
                    } catch (Exception e) {
                        KLog.e(e);
                    }
                }
            }
        });
        binding.rcContent.setLayoutManager(new LinearLayoutManager(getContext()));
//        binding.rcContent.setNestedScrollingEnabled(false);
        binding.rcContent.setFocusable(false);
        binding.rcContent.setFocusableInTouchMode(false);
        observable = new LogObservable();
        final Bundle argument = getArguments();
        viewModel.init(RepositoryInjection.providerLogRepository(),
                argument.getString(ActivityEvent.DEVICE_MAC), argument.getByte(ActivityEvent.DEVICE_PORT, (byte) 0x0));
        viewModel.initAdapter().compose(this.<LogExtra>bindToLifecycle()).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<LogExtra>() {
            @Override
            public void accept(LogExtra extra) throws Exception {
                adapter = new LogAdapter(extra);
                binding.rcContent.setAdapter(adapter);
                viewModel.logs.observe(LogFragment.this, observable);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            viewModel.getExtra().compose(this.<LogExtra>bindToLifecycle()).subscribeOn(Schedulers.io()).subscribe(new Consumer<LogExtra>() {
                @Override
                public void accept(LogExtra extra) throws Exception {
                    adapter.setExtra(extra);
                    binding.rcContent.scrollToPosition(0);
                }
            });

        }
    }

    @Override
    public void onResume() {
        if (adapter != null) {
            viewModel.getExtra().compose(this.<LogExtra>bindToLifecycle()).subscribeOn(Schedulers.io()).subscribe(new Consumer<LogExtra>() {
                @Override
                public void accept(LogExtra extra) throws Exception {
                    adapter.setExtra(extra);
                }
            });
        }
        super.onResume();
    }

    private void bindEvent() {
        viewModel.show.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                if (result) {
                    binding.umeFilter.collapse();
                } else {
                    binding.umeFilter.expand();
                }
            }
        });
        viewModel.auto.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvAutoTigger.setSelected(result);
            }
        });
        viewModel.timeOn.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvTimeToOn.setSelected(result);
            }
        });
        viewModel.timeOff.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvTimeToOff.setSelected(result);
            }
        });
        viewModel.cycle.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvCycles.setSelected(result);
            }
        });
        viewModel.schedules.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvSchedules.setSelected(result);
            }
        });
        viewModel.alarms.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvAlarm.setSelected(result);
            }
        });
        viewModel.alert.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvAlerts.setSelected(result);
            }
        });
        viewModel.automation.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                binding.tvAutomations.setSelected(result);
            }
        });
    }

    private void registerMassage() {
        Messenger.getDefault().register(this, REFRESH_LOG, new BindingAction() {
            @Override
            public void call() {
                KLog.e("refresh log");
                viewModel.logs.removeObservers(LogFragment.this);
                viewModel.refresh();
                viewModel.logs.observe(LogFragment.this, observable);
            }
        });
    }

    private void unregisterMassage() {
        Messenger.getDefault().unregister(this);
    }

    private class LogObservable implements Observer<PagedList<Log>> {
        @Override
        public void onChanged(@Nullable PagedList<Log> logs) {
            adapter.submitList(logs);
            binding.rcContent.scrollToPosition(position);
        }
    }
}

